package com.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.domain.Cart;
import com.domain.Goods;
import com.domain.User;
import com.service.AddresService;
import com.service.CartService;
import com.service.Impl.AddresServiceImpl;
import com.service.Impl.CartServiceImpl;
import com.service.Impl.UsersServiceImpl;
import com.service.UsersService;

@WebServlet("/buyServlet")
public class buyServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取域中数据
        HttpSession session = request.getSession();
        //获取登录用户名
        String username = (String) session.getAttribute("username");
        if(username == null) {
            request.getRequestDispatcher("/page/login1.jsp").forward(request, response);
        }
        System.out.println(username);
        //获取域中商品
        Goods goods = (Goods) session.getAttribute("goods");
        //获取数量
        String value = request.getParameter("number");
        if(value == null) {
            return;
        }

        UsersService usersService = new UsersServiceImpl();
        CartService cartService = new CartServiceImpl();
        AddresService addressService = new AddresServiceImpl();

        //根据名字查询用户
        User user = usersService.findByName(username);
        int uid = user.getId();//得到用户ID值

        //封装
        Cart cart = new Cart();
        cart.setUserid(user.getId());
        cart.setNums(Integer.parseInt(value));
        cart.setPrice(goods.getSalesprice());
        cart.setGoodsid(goods.getId());
        //添加进购物车
        cartService.addGoods(cart);

        //重定向到购买页面
        response.sendRedirect("/woniusales/page/shopping.jsp");
    }
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}
